/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.blacklist;

import com.wtkj.vo.dzzf.base.kfzx.ListRealRecord;
import com.wttech.dzzf.process.dao.BlackListInfoDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.ObuTemp;
import com.wttech.dzzf.process.model.user.Obu;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 记录OBU黑名单的上传情况
 *
 * @author MaShibo
 * @date 2017/12/22.
 */
@Service
public class RecordBlObuInfosService {

	private static final Logger LOGGER = LoggerFactory.getLogger(RecordBlObuInfosService.class);

	@Resource
	private BlackListInfoDao blackListInfoDao;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private BaseInfoService baseInfoService;

	private void process() {
		blackListInfoDao.resetBlObuType1();
		while (true) {
			List<ListRealRecord> records = blackListInfoDao.queryObuBlListInfos(1, DEFAULT_PROCESS_NUM);
			if (CollectionUtils.isEmpty(records)) {
				executor.shutdown();
				LOGGER.info("执行完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(records.size());
			records.forEach(record -> futures.add(executor.submit(() -> {
				String obuId = record.getObuId();
				LOGGER.info("开始处理OBU 【{}】", obuId);
				try {
					Obu obu = blackListInfoDao.queryBsObuById(obuId);
					createObuTemp(obuId, obu == null ? ObuTemp.STATE_UNUPLOAD : ObuTemp.STATE_UPLODED);
					blackListInfoDao.updateBlObuType1(record.getListID(), 0);
				} catch (Exception e) {
					LOGGER.error(e.getMessage(), e);
				}
				return null;
			})));
			baseInfoService.getFutureResult(futures);
		}
	}

	private void createObuTemp(String obuId, Integer state) {
		ObuTemp temp = new ObuTemp();
		temp.setObuId(obuId);
		temp.setState(state);
		try {
			transferUserInfoDao.createTestObjcet(temp);
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		RecordBlObuInfosService service = context.getBean(RecordBlObuInfosService.class);
		service.process();
	}
}
